<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
// +----------------------------------------------------------------------+
// | Treacle PHP Framework Version 0.10                                   |
// +----------------------------------------------------------------------+
// | Copyright (c) 2007 Treacle.cn All rights reserved.					  |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the 'License');      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an 'AS IS' BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: BoPo <ibopo@126.com>										  |
// +----------------------------------------------------------------------+
/**
 * URI请求处理文件
 *
 * @author BoPo <ibopo@126.com>
 * @link http://www.treacle.cn/
 * @copyright Copyright &copy; 2007 Treacle
 * @license http://www.treacle.cn/license/
 * @version $Id $
 * @package libraries
 */
/**
 * URI请求处理
 *
 * @package libraries
 * @author BoPo <ibopo@126.com>
 * @since 0.10
 * @version	$Id $
 */
class TRouter
{
	/**
	 * 读取配置
	 * 
	 * @var array
	 */
	private $config	= '';
	/**
	 * URI 字符串
	 * 
	 * @var string
	 */
	private $uri_string	= '';
	/**
	 * URI 分割后转换的数组
	 * 
	 * @var array
	 */
	private $segments = array();
	/**
	 * $segments 重组后的数组
	 *
	 * @var array
	 */
	private $rsegments = array();
	/**
	 * 捕获控制器的名称
	 * 
	 * @var string
	 */
	private $class = '';
	/**
	 * 构造函数
	 * 
	 * Runs the route mapping function.
	 */
	public function __construct()
	{
		$this->config = Configure::item_array();
		$this->_set_route_mapping();
	}
	/**
	 * 设置 URI 和分解等操作
	 * 
	 * @access	private
	 * @return	void
	 */
	private function _set_route_mapping()
	{
		// 获取uri字符串
		$this->uri_string = $this->_get_uri_string();

		if ($this->config['enable_query_strings'] === true AND isset($_GET[$this->config['controller_trigger']]))
		{
			$this->_set_class(trim($this->_filter_uri($_GET[$this->config['controller_trigger']])));
			return false;
		}
		// uri字符串为 "/" 则设置为空
		if ($this->uri_string == '/' || $this->uri_string == '')
		{
			$this->_set_class($this->config['default_controller']);return ;
		}
		// 拆分 URI.
		foreach(explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $this->uri_string)) as $val)
		{
			// 验证 URI 字符串
			$val = trim($this->_filter_uri($val));
			if ($val != '')
			{
				$this->segments[] = $val;
			}
		}
		// 解析路由
		$this->_parse_routes();
		// 重组URI分割的索引
		$this->_reindex_segments();
	}
	/**
	 * 编译URI分割
	 * 
	 * @access	private
	 * @param	array
	 * @param	bool
	 * @return	void
	 */
	private function _compile_segments($segments = array())
	{
		$segments = $this->_validate_segments($segments);
		if (count($segments) == 0) return false;
		$this->_set_class($segments[0]);
		$this->rsegments = $segments;
	}
	/**
	 * 验证控制器是否存在,如果存在就返回，否则返回空数组
	 * 
	 * @access	private
	 * @param	array
	 * @return	array
	 */
	private function _validate_segments($segments)
	{
		// 判断控制器文件是否存在?
		if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
		{
			return $segments;
		}
		return array();
	}
	/**
	 * 重组 URI分割
	 * 
	 * 去除0开始的数组,并修改其key,修改为1开始(注释需完善)
	 * @access	private
	 * @return	void
	 */
	private function _reindex_segments()
	{
		// Is the routed segment array different then the main segment array?
		$diff = (count(array_diff($this->rsegments, $this->segments)) == 0) ? false : true;

		$i = 1;
		foreach ($this->segments as $val)
		{
			$this->segments[$i++] = $val;
		}
		unset($this->segments[0]);

		if ($diff == false)
		{
			$this->rsegments = $this->segments;
		}
		else
		{
			$i = 1;
			foreach ($this->rsegments as $val)
			{
				$this->rsegments[$i++] = $val;
			}
			unset($this->rsegments[0]);
		}
	}
	/**
	 * 获得 URI 字符串
	 * @access	private
	 * @return	string
	 */
	private function _get_uri_string()
	{
		// 如果是 AUTO 模式
		if (strtoupper($this->config['uri_protocol']) == 'AUTO')
		{
			// GET 请求有值
			if (is_array($_GET) AND count($_GET) == 1)
			{
				// of PHP we can not pass function call directly into it
				$keys = array_keys($_GET);
				return current($keys);
			}

			// 判断 PATH_INFO 是否存在?
			$path = (isset($_SERVER['PATH_INFO']))?$_SERVER['PATH_INFO']:@getenv('PATH_INFO');
			if ($path != '' AND $path != "/".SELF)
			{
				return $path;
			}
			// 没有PATH_INFO,那么寻找QUERY_STRING?
			$path =  (isset($_SERVER['QUERY_STRING']))
				?$_SERVER['QUERY_STRING']
				:@getenv('QUERY_STRING');
			if ($path != '')
			{
				return $path;
			}
			// 没有QUERY_STRING?判断 ORIG_PATH_INFO 是否存在?
			$path = (isset($_SERVER['ORIG_PATH_INFO']))?$_SERVER['ORIG_PATH_INFO']:@getenv('ORIG_PATH_INFO');
			if ($path != '' AND $path != "/".SELF)
			{
				return $path;
			}
			return '';
		}
		else
		{
			$uri = strtoupper($this->uri_protocol);
			// 如果是 REQUEST_URI 模式
			if ($uri == 'REQUEST_URI') return $this->_parse_request_uri();
			return (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri);
		}
	}
	/**
	 * 解析 REQUEST_URI
	 * 
	 * @access	private
	 * @return	string
	 */
	private function _parse_request_uri()
	{
		if ( ! isset($_SERVER['REQUEST_URI']) OR $_SERVER['REQUEST_URI'] == '')
		{
			return '';
		}
		$request_uri = preg_replace("|/(.*)|", "\\1", str_replace("\\", "/", $_SERVER['REQUEST_URI']));
		if ($request_uri == '' OR $request_uri == SELF)
		{
			return '';
		}
		$fc_path = FCPATH;
		if (strpos($request_uri, '?') !== false)
		{
			$fc_path .= '?';
		}
		$parsed_uri = explode("/", $request_uri);
		$i = 0;
		foreach(explode("/", $fc_path) as $segment)
		{
			if (isset($parsed_uri[$i]) AND $segment == $parsed_uri[$i])
			{
				$i++;
			}
		}
		$parsed_uri = implode("/", array_slice($parsed_uri, $i));
		if ($parsed_uri != '')
		{
			$parsed_uri = '/'.$parsed_uri;
		}
		return $parsed_uri;
	}
	/**
	 * 过滤URI分割(通过正则表达式来验证)
	 * 
	 * @access	private
	 * @param	string
	 * @return	string
	 */
	private function _filter_uri($str)
	{
		if ($this->config['permitted_uri_chars'] != '')
		{
			if ( ! preg_match("|^[".preg_quote($this->config['permitted_uri_chars'])."]+$|i", $str))
			{
				throw new TSystemException('uri_disallowed_characters',$str);
			}
		}
		return $str;
	}
	/**
	 * 解析路由(完善中)
	 * 
	 * @access	private
	 * @return	void
	 */
	private function _parse_routes()
	{
		$this->_compile_segments($this->segments);
	}
	/**
	 * 设置 class 名称(内部使用)
	 * 
	 * @access	private
	 * @param	string
	 * @return	void
	 */
	private function _set_class($class)
	{
		$this->class = $class;
	}
	/**
	 * 获取class，用来确定控制器的名称
	 * @access	public
	 * @return	string
	 */
	public function fetch_class()
	{
		return $this->class;
	}
	/**
	 * 获取全部uri段
	 *
	 * @return array
	 */
	public function get_rsegments()
	{
		return $this->rsegments;
	}
	/**
	 * 获取URI分割的某一部分
	 * 
	 * @access	public
	 * @param	integer
	 * @param	bool
	 * @return	string
	 */
	public function segment($n, $no_result = false)
	{
		return ( ! isset($this->segments[$n])) ? $no_result : $this->segments[$n];
	}
	/**
	 * 获取URI分割的某一部分(重组)
	 * 
	 * @access	public
	 * @param	integer
	 * @param	bool
	 * @return	string
	 */
	public function rsegment($n, $no_result = false)
	{
		return ( ! isset($this->rsegments[$n])) ? $no_result : $this->rsegments[$n];
	}
	/**
	 * 以一个数组的key来获取来自URI字符串，重组为数组
	 *
	 *	www.your-site.com/user/search/name/joe/location/UK/gender/male
	 *
	 * array (
	 *			name => joe
	 *			location => UK
	 *			gender => male
	 *		 )
	 *
	 * @access	public
	 * @param	integer	the starting segment number
	 * @param	array	an array of default values
	 * @return	array
	 */
	public function uri_to_assoc($n = 3, $default = array())
	{
		return $this->_uri_to_assoc($n, $default, 'segment');
	}
	
	/**
	 * 将一个uri转换成数组(重组模式)
	 */
	public function ruri_to_assoc($n = 3, $default = array())
	{
		return $this->_uri_to_assoc($n, $default, 'rsegment');
	}
	
	/**
	 * 将一个uri转换成数组
	 * 
	 * @access	private
	 * @param	integer	the starting segment number
	 * @param	array	an array of default values
	 * @param	string	which array we should use
	 * @return	array
	 */
	private function _uri_to_assoc($n = 3, $default = array(), $which = 'segment')
	{
		if ($which == 'segment')
		{
			$total_segments = 'total_segments';
			$segment_array	= 'segment_array';
		}
		else
		{
			$total_segments = 'total_rsegments';
			$segment_array	= 'rsegment_array';
		}

		if ( ! is_numeric($n))
		{
			return $default;
		}
		if (isset($this->keyval[$n]))
		{
			return $this->keyval[$n];
		}
		if ($this->$total_segments() < $n)
		{
			if (count($default) == 0)
			{
				return array();
			}
			$retval = array();
			foreach ($default as $val)
			{
				$retval[$val] = false;
			}
			return $retval;
		}
		$segments	= array_slice($this->$segment_array(), ($n - 1));
		$i			= 0;
		$lastval	= '';
		$retval		= array();
		foreach ($segments as $seg)
		{
			if ($i % 2)
			{
				$retval[$lastval] = $seg;
			}
			else
			{
				$retval[$seg] = false;
				$lastval = $seg;
			}
			$i++;
		}
		if (count($default) > 0)
		{
			foreach ($default as $val)
			{
				if ( ! array_key_exists($val, $retval))
				{
					$retval[$val] = false;
				}
			}
		}
		$this->keyval[$n] = $retval;
		return $retval;
	}
	
	/**
	 * 将一个数组换成URI字符串转
	 * 
	 * @access	public
	 * @param	array	an associative array of key/values
	 * @return	array
	 */
	public function assoc_to_uri($array)
	{
		$temp = array();
		foreach ((array)$array as $key => $val)
		{
			$temp[] = $key;
			$temp[] = $val;
		}
		return implode('/', $temp);
	}
	
	/**
	 * Fetch a URI Segment and add a trailing slash
	 *
	 * @access	public
	 * @param	integer
	 * @param	string
	 * @return	string
	 */
	public function slash_segment($n, $where = 'trailing')
	{
		return $this->_slash_segment($n, $where, 'segment');
	}
	
	/**
	 * Fetch a URI Segment and add a trailing slash
	 * 
	 * @access	public
	 * @param	integer
	 * @param	string
	 * @return	string
	 */
	public function slash_rsegment($n, $where = 'trailing')
	{
		return $this->_slash_segment($n, $where, 'rsegment');
	}
	
	/**
	 * Fetch a URI Segment and add a trailing slash - helper function
	 * 
	 * @access	private
	 * @param	integer
	 * @param	string
	 * @param	string
	 * @return	string
	 */
	private function _slash_segment($n, $where = 'trailing', $which = 'segment')
	{
		if ($where == 'trailing')
		{
			$trailing	= '/';
			$leading	= '';
		}
		elseif ($where == 'leading')
		{
			$leading	= '/';
			$trailing	= '';
		}
		else
		{
			$leading	= '/';
			$trailing	= '/';
		}
		return $leading.$this->$which($n).$trailing;
	}
	
	/**
	 * 返回以数组形式的URI分割
	 * 
	 * @access	public
	 * @return	array
	 */
	public function segment_array()
	{
		return $this->segments;
	}
	
	/**
	 * 返回重组以数组形式的URI分割
	 * 
	 * @access	public
	 * @return	array
	 */
	public function rsegment_array()
	{
		return $this->rsegments;
	}
	
	/**
	 * 获得URI分割数组的维数
	 * 
	 * @access	public
	 * @return	integer
	 */
	public function total_segments()
	{
		return count($this->segments);
	}
	
	/**
	 * 获得重组URI分割数组的维数
	 * 
	 * @access	public
	 * @return	integer
	 */
	public function total_rsegments()
	{
		return count($this->rsegments);
	}
	
	/**
	 * 获得 URI string
	 *
	 * @access	public
	 * @return	string
	 */
	public function uri_string()
	{
		return $this->uri_string;
	}
	
	/**
	 * 获得一个重组的 URI string (如果末尾没有"/",自动补上)
	 * 
	 * @access	public
	 * @return	string
	 */
	public function ruri_string()
	{
		return '/'.implode('/', $this->rsegment_array()).'/';
	}
}
/*
+---------------------------------------------------------------------------
|   Last Modified By BoPo
|   Date: Wed Nov 07 23:56:00 CST 2007
+--------------------------------------------------------------------------
*/
?>